package xuecheng.tool.json.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import xuecheng.tool.json.JsonUtils;

/**
 * fast-json 实现
 *
 * @author PengXueCheng
 * @version 1.0.0
 */
public class JsonUtilsFastJsonImpl implements JsonUtils {

    private static final JsonUtilsFastJsonImpl INSTANCE = new JsonUtilsFastJsonImpl();

    private JsonUtilsFastJsonImpl() {}

    public static JsonUtilsFastJsonImpl getInstance() {
        return INSTANCE;
    }

    @Override
    public String toJson(Object src) {
        return JSON.toJSONString(src);
    }

    @Override
    public <T> T fromJsonAsObject(String json, Class<T> classOfT) {
        return JSON.parseObject(json, classOfT);
    }

    @Override
    public <T> List<T> fromJsonAsArray(String json, Class<T> classOfT) {
        return JSON.parseArray(json, classOfT);
    }

    @Override
    public String getAsString(String json, String memberName) {
        return JSONObject.parseObject(json).getString(memberName);
    }

    @Override
    public int getAsInt(String json, String memberName) {
        return JSONObject.parseObject(json).getInteger(memberName);
    }

    @Override
    public Date getAsDate(String json, String memberName) {
        return JSONObject.parseObject(json).getDate(memberName);
    }

    @Override
    public boolean getAsBoolean(String json, String memberName) {
        return JSONObject.parseObject(json).getBoolean(memberName);
    }

    @Override
    public <T> T getAsObj(String json, String memberName, Class<T> classOfT) {
        JSONObject jsonObject = JSONObject.parseObject(json).getJSONObject(memberName);
        return jsonObject.toJavaObject(classOfT);
    }

}
